//
//  MyacontViewController.m
//  Distributor
//
//  Created by 主事丫环 on 2019/5/15.
//  Copyright © 2019 主事丫环. All rights reserved.
//

#import "MyacontViewController.h"
#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>
#import "APAuthInfo.h"
#import "APRSASigner.h"
#import "DISaccmodel.h"

@interface MyacontViewController ()
@property(nonatomic,strong)DISaccmodel *alipayModel;
@property (weak, nonatomic) IBOutlet UILabel *wechatGoshouquan;
@property (weak, nonatomic) IBOutlet UILabel *weibangdingWechat;
@property (weak, nonatomic) IBOutlet UILabel *weibandingAlipay;
@property (weak, nonatomic) IBOutlet UILabel *alipayGoshouquna;
@property (weak, nonatomic) IBOutlet UISwitch *wechaSwith;
@property (weak, nonatomic) IBOutlet UISwitch *alipaySwith;
@property (weak, nonatomic) IBOutlet UIImageView *wechatImage;
@property (weak, nonatomic) IBOutlet UILabel *wechatName;
@property (weak, nonatomic) IBOutlet UIImageView *alipayImage;
@property (weak, nonatomic) IBOutlet UILabel *alipayname;


@end

@implementation MyacontViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的账户";
    [self.leftbutton setImage:imgname(@"left_icon") forState:(UIControlStateNormal)];
    //self.headerImage = [[UIImage alloc]init];
    self.alipayModel = [[DISaccmodel alloc]init];
    self.wechatName.hidden = YES;
    self.wechatImage.hidden = YES;
    self.alipayname.hidden = YES;
    self.alipayImage.hidden = YES;
    
    kWeakSelf;
    
    if (!strIsEmpty(_model.wx_image_url)) {
        self.wechatGoshouquan.text = @"切换账号";
        self.weibangdingWechat.hidden = YES;
        self.wechatName.hidden = NO;
        self.wechatImage.hidden = NO;
        [self.wechatImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",weakSelf.model.wx_image_url]]];
        
        if (self.model.wx_name == nil || self.model.wx_name == NULL) {
            self.wechatName.hidden = YES;
        } else {
            self.wechatName.text = [NSString stringWithFormat:@"%@",self.model.wx_name];
        }
    }
    
    if (!strIsEmpty(_model.alipay_image_url)) {
        self.alipayGoshouquna.text = @"切换账号";
        self.weibandingAlipay.hidden = YES;
        self.alipayname.hidden = NO;
        self.alipayImage.hidden = NO;
        [self.alipayImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",weakSelf.model.alipay_image_url]]];
        
        if (self.model.alipay_name == nil || self.model.alipay_name == NULL) {
            self.alipayname.hidden = YES;
        } else {
            self.alipayname.text = [NSString stringWithFormat:@"%@",weakSelf.model.alipay_name];
        }
    }
    
    if (!strIsEmpty(_model.type)) {
        if ( [_model.type integerValue] == 1) {
            self.wechaSwith.on = YES;
            self.alipaySwith.on = NO;
        } else if ([_model.type integerValue] == 2){
            self.alipaySwith.on = YES;
            self.wechaSwith.on = NO;
        }
    } else {
        self.wechaSwith.on = NO;
        self.alipaySwith.on = NO;
    }
    
    if (!self.model) {
        self.model = [[CSPersonModel alloc]init];
        [self request];
    }
    
    [Center addObserver:self selector:@selector(zhifubao:) name:@"shouquanSuccess" object:nil];
    
    [Center addObserver:self selector:@selector(wechataction:) name:@"wechatshouquanSuccess" object:nil];
    // Do any additional setup after loading the view from its nib.
}

-(void)request{
    kWeakSelf;
    [NetWorkTool POST:CcentenInfo param:nil success:^(id dic) {
        
        [self.model setValuesForKeysWithDictionary:[dic objectForKey:@"data"]];
        
        if (!strIsEmpty(_model.wx_image_url)) {
            self.wechatGoshouquan.text = @"切换账号";
            self.weibangdingWechat.hidden = YES;
            self.wechatName.hidden = NO;
            self.wechatImage.hidden = NO;
            [self.wechatImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",weakSelf.model.wx_image_url]]];
            
            if (self.model.wx_name == nil || self.model.wx_name == NULL) {
                self.wechatName.hidden = YES;
            } else {
                self.wechatName.text = [NSString stringWithFormat:@"%@",self.model.wx_name];
            }
        }
        
        if (!strIsEmpty(_model.alipay_image_url)) {
            self.alipayGoshouquna.text = @"切换账号";
            self.weibandingAlipay.hidden = YES;
            self.alipayname.hidden = NO;
            self.alipayImage.hidden = NO;
            [self.alipayImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",weakSelf.model.alipay_image_url]]];
            
            if (self.model.alipay_name == nil || self.model.alipay_name == NULL) {
                self.alipayname.hidden = YES;
                self.alipayname.backgroundColor = [UIColor cyanColor];
            } else {
                self.alipayname.text = [NSString stringWithFormat:@"%@",weakSelf.model.alipay_name];
            }
        }
        
        if (!strIsEmpty(self->_model.type)) {
            if ( [self->_model.type integerValue] == 1) {
                self.wechaSwith.on = YES;
                self.alipaySwith.on = NO;
                
            } else if ([self->_model.type integerValue] == 2){
                self.alipaySwith.on = YES;
                self.wechaSwith.on = NO;
            }
        } else {
            self.wechaSwith.on = NO;
            self.alipaySwith.on = NO;
        }
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
    } fail:^(NSError *error) {
        
    } needUser:YES];
}
#pragma mark - 微信授权成功
-(void)wechataction:(NSNotification *)no{
    NSString *code = [NSString stringWithFormat:@"%@",[no.userInfo objectForKey:@"code"]];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:1];
    param[@"code"] =code;
    param[@"phone"] = NOTNIL(_model.phone);
    kWeakSelf;
    [NetWorkTool POST:wxAppLogin param:param success:^(id dic) {
        [weakSelf request];
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
    } fail:^(NSError *error) {
        
    } needUser:YES];
}
#pragma mark - 设置微信为默认账户
- (IBAction)wechatswith:(UISwitch *)sender {
    
    if (![self.model.type isEqualToString:@"1"]) {
        //微信不是默认账户的时候
        if (strIsEmpty(_model.wx_image_url)) {
            ShowToastWithText(@"请授权微信");
            self.wechaSwith.on = NO;
        }else{
            //设置微信为默认账户
            [self shwotiixnawith:@"1"];
        }
    }else{
        //微信是默认账户的时候
        if (strIsEmpty(_model.alipay_image_url)) {
            //如果没有支付宝授权，不能关闭微信的默认账户
            ShowToastWithText(@"请授权支付宝");
            self.wechaSwith.on = YES;
        }else{
            //设置支付宝为默认账户
            [self shwotiixnawith:@"2"];
        }
    }
    
}
#pragma mark - 设置支付宝为默认账户
- (IBAction)alipayAcrti:(UISwitch *)sender {
    if (![self.model.type isEqualToString:@"2"]) {
        //支付宝不是默认账户的时候
        if (strIsEmpty(_model.alipay_image_url)) {
            ShowToastWithText(@"请授权支付宝");
            self.alipaySwith.on = NO;
        }else{
            //设置支付宝为默认账户
            [self shwotiixnawith:@"2"];
        }
    }else{
        //支付宝是默认账户的时候
        if (strIsEmpty(_model.wx_image_url)) {
            //如果没有微信授权，不能关闭支付宝的默认账户
            ShowToastWithText(@"请授权微信");
            self.alipaySwith.on = YES;
        }else{
            //设置微信为默认账户
            [self shwotiixnawith:@"1"];
        }
    }
}

-(void)zhifubao:(NSNotification *)no{
    NSString *code = [NSString stringWithFormat:@"%@",[no.userInfo objectForKey:@"result"]];
    
    NSArray  *array = [code componentsSeparatedByString:@"="];
    NSString *sfdsfs = [NSString stringWithFormat:@"%@",array[4]];
    NSString *codelst = [sfdsfs substringToIndex:sfdsfs.length - 6];
    KMyLog(@"沙发范德萨发生%@",codelst);
    KMyLog(@"沙发范德萨发生%@",code);
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:1];
    param[@"code"] =codelst;
    param[@"phone"] =_model.phone;
    kWeakSelf;
    [NetWorkTool POST:aliPayAppLogin param:param success:^(id dic) {
        KMyLog(@"sfas超市%@",dic);
        [NetWorkTool POST:CcentenInfo param:nil success:^(id dic) {
            
            [self.model setValuesForKeysWithDictionary:[dic objectForKey:@"data"]];
            
            if (!strIsEmpty(_model.wx_image_url)) {
                self.wechatGoshouquan.text = @"切换账号";
                self.weibangdingWechat.hidden = YES;
                self.wechatName.hidden = NO;
                self.wechatImage.hidden = NO;
                [self.wechatImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",weakSelf.model.wx_image_url]]];
                
                if (self.model.wx_name == nil || self.model.wx_name == NULL) {
                    self.wechatName.hidden = YES;
                } else {
                    self.wechatName.text = [NSString stringWithFormat:@"%@",self.model.wx_name];
                }
            }
            
            if (!strIsEmpty(self->_model.alipay_image_url)) {
                self.alipayGoshouquna.text = @"切换账号";
                self.weibandingAlipay.hidden = YES;
                self.alipayname.hidden = NO;
                self.alipayImage.hidden = NO;
                [self.alipayImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",weakSelf.model.alipay_image_url]]];
                
                if (self.model.alipay_name == nil || self.model.alipay_name == NULL) {
                    self.alipayname.hidden = YES;
                    self.alipayname.backgroundColor = [UIColor cyanColor];
                } else {
                    self.alipayname.text = [NSString stringWithFormat:@"%@",weakSelf.model.alipay_name];
                }
            }
            
            if (!strIsEmpty(self->_model.type)) {
                if ( [self->_model.type integerValue] == 1) {
                    self.wechaSwith.on = YES;
                } else if ([self->_model.type integerValue] == 2){
                    self.alipaySwith.on = YES;
                }
            } else {
                self.wechaSwith.on = NO;
                self.alipaySwith.on = NO;
            }
            
        } other:^(id dic) {
            ShowToastWithText(dic[@"msg"]);
        } fail:^(NSError *error) {
            
        } needUser:YES];
    } other:^(id dic) {
        
    } fail:^(NSError *error) {
        
    } needUser:YES];
}

-(void)shwotiixnawith:(NSString *)type{
    kWeakSelf;
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:1];
    param[@"type"] = type;
    [NetWorkTool POST:setDefaultTX param:param success:^(id dic) {
        ShowToastWithText(@"修改成功");
        if ([type isEqualToString:@"1"]) {
            //设置微信为默认账户成功
            weakSelf.model.type = @"1";
            weakSelf.wechaSwith.on = YES;
            weakSelf.alipaySwith.on = NO;
        }else{
            //设置支付宝为默认账户成功
            weakSelf.model.type = @"2";
            weakSelf.wechaSwith.on = NO;
            weakSelf.alipaySwith.on = YES;
        }
        
    } other:^(id dic) {
        if ([type isEqualToString:@"1"]) {
            //设置微信失败
            weakSelf.wechaSwith.on = NO;
        }else{
            //设置支付宝失败
            weakSelf.alipaySwith.on = NO;
        }
    } fail:^(NSError *error) {
        if ([type isEqualToString:@"1"]) {
            //设置微信失败
            weakSelf.wechaSwith.on = NO;
        }else{
            //设置支付宝失败
            weakSelf.alipaySwith.on = NO;
        }
    } needUser:YES];
}

- (IBAction)wechatAction:(UIButton *)sender {
    if ([WXApi isWXAppInstalled]) {
        SendAuthReq* req =[[SendAuthReq alloc ] init];
        req.scope = @"snsapi_userinfo";
        req.state = @"wx_oauth2_authorization_state";
        
        [WXApi sendReq:req];
    } else {
        //没安装维修
    }
}

-(void)tencentDidLogin {
    NSLog(@"yes");
}

- (IBAction)alipayAction:(UIButton *)sender {
    //    [NetWorkTool POST:@"http://192.168.2.205:8088/cs_pay/agentAlipayToLogin" param:nil
    //              success:^(id dic) {
    //                KMyLog(@"dasf%@",dic);
    //              } other:^(id dic) {
    //
    //              } fail:^(NSError *error) {
    //
    //              } needUser:YES];
    //    return;
    
    // 重要说明
    // 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
    // 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
    // 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *pid = @"2088431820896382";
    NSString *appID = @"2019051664688524";
    
    // 如下私钥，rsa2PrivateKey 或者 rsaPrivateKey 只需要填入一个
    // 如果商户两个都设置了，优先使用 rsa2PrivateKey
    // rsa2PrivateKey 可以保证商户交易在更加安全的环境下进行，建议使用 rsa2PrivateKey
    // 获取 rsa2PrivateKey，建议使用支付宝提供的公私钥生成工具生成，
    // 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
    NSString *rsa2PrivateKey = @"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDOwQWtRqeGzAo+XhpnsCMlaJQa8rPtt38BJiulWx+wIP9X6gbSJQP0gwT29rFCUd8DAfOOv8N8nn3Z1RWqovv1x2AN/Q00nj13PdeZbpJafY0epuFyPQB0Fhpw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UrGet53DKt3ehwmQdFgsQKBgBCped9lF6/jFQCUor9qySUs/+BPnW/NRAhzcCSZvblXOnz9nULxVZL4jYN3LFdaXbtQFS4PtKBb7r8CTCdGkE2sq+x0v7Jo4AZObHsG+gK22s9/d+h9w9jmG44VzTxFozWZMsYCXZriHuR6AhM2XTUB01DiRXM4r3j5ol7DOOaVAoGAIipTLW4w3tbBDzxfcJrX0B6X1FLPcxc9vNm3C6RVdQl5kwBchnWaYL3LBrHQtiOAv2tg5Qow9Eucv1R/N0WqIq4/MGo53zuUHwa+VVyWMBadOrfiOXsyFXLpVEDG5/kIdqaMUi/KlKAFUsrBMkB9TyKkCMqc2X5+2RYPoDpwBVU=";
    NSString *rsaPrivateKey = @"";
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    kWeakSelf;
    //pid和appID获取失败,提示
    if ([pid length] == 0 ||
        [appID length] == 0 ||
        ([rsa2PrivateKey length] == 0 && [rsaPrivateKey length] == 0)) {
        UIAlertController *alert = [UIAlertController
                                    alertControllerWithTitle:@"提示"
                                    message:@"缺少pid或者appID或者私钥,请检查参数设置"
                                    preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction
                                 actionWithTitle:@"知道了"
                                 style:UIAlertActionStyleDefault
                                 handler:^(UIAlertAction *action){
            
        }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:^{ }];
        return;
    }
    
    //生成 auth info 对象
    APAuthInfo *authInfo = [APAuthInfo new];
    authInfo.pid = pid;
    authInfo.appID = appID;
    
    //auth type
    NSString *authType = [[NSUserDefaults standardUserDefaults] objectForKey:@"authType"];
    if (authType) {
        authInfo.authType = authType;
    }
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"jingxiaoshangzsyh";
    
    // 将授权信息拼接成字符串
    NSString *authInfoStr = [authInfo description];
    NSLog(@"authInfoStr = %@",authInfoStr);
    
    // 获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    NSString *signedString = nil;
    APRSASigner* signer = [[APRSASigner alloc] initWithPrivateKey:((rsa2PrivateKey.length > 1)?rsa2PrivateKey:rsaPrivateKey)];
    if ((rsa2PrivateKey.length > 1)) {
        signedString = [signer signString:authInfoStr withRSA2:YES];
    } else {
        signedString = [signer signString:authInfoStr withRSA2:NO];
    }
    
    // 将签名成功字符串格式化为订单字符串,请严格按照该格式
    if (signedString.length > 0) {
        authInfoStr = [NSString stringWithFormat:@"%@&sign=%@&sign_type=%@", authInfoStr, signedString, ((rsa2PrivateKey.length > 1)?@"RSA2":@"RSA")];
        [[AlipaySDK defaultService] auth_V2WithInfo:authInfoStr
                                         fromScheme:appScheme
                                           callback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
            //weakSelf.ALIPAY =[NSString stringWithFormat:@"%@",authCode];
            [weakSelf zhifubaosucess:authCode];
        }];
    }
}

-(void)processAuth_V2Result:(NSURL*)resultUrl standbyCallback:(CompletionBlock)completionBlock{
    KMyLog(@"dsfsfsd%@",resultUrl);
}
#pragma mark - 支付宝授权成功
-(void)zhifubaosucess:(NSString *)aucode{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:1];
    param[@"code"] =aucode;
    param[@"phone"] =NOTNIL(self.model.phone);
    kWeakSelf;
    [NetWorkTool POST:aliPayAppLogin param:param success:^(id dic) {
        //请求个人数据
        [weakSelf request];
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
    } fail:^(NSError *error) {
        
    } needUser:YES];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
